import json

from django.db.models import Count
from django.http import JsonResponse
from db_man_app.models import Major, Department, Class
# Create your models here.
def get_all(request):
    # 获取所有专业及其关联数据
    majors = Major.objects.annotate(
        class_count=Count('class', distinct=True)
    ).select_related('department').all()
    # 构建返回数据
    tableData = []
    for major in majors:
        tableData.append({
            'major_name': major.major_name,
            'college_name': major.department.department_name,
            'class_name': major.class_count
        })
    return JsonResponse({
        'tableData': tableData,
        'status': 'success',
        'message': '专业数据获取成功'
    })


#给表单获得学院信息
def get_college_form(request):
    try:
        colleges = Department.objects.all().values('department_id', 'department_name')
        return JsonResponse({
            'code': 200,
            'message': 'success',
            'data': list(colleges)
        })
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': str(e),
            'data': []
        })


def add_one(request):
    data=json.loads(request.body)
    department_id=data['department_id']
    major_name=data['major_name']
    try:
        Major.objects.create(major_name=major_name, department_id=department_id)
        return JsonResponse(1,safe=False)
    except Exception as e:
        return JsonResponse(0,safe=False)


def updata_one(request):
    data=json.loads(request.body)
    old_name=data['old_major_name']
    major_name=data['formData']['major_name']
    college_name=data['formData']['department_name']
    try:
        #从数据库找college_name对应的id
        college_id=Department.objects.get(department_name=college_name).department_id
        #更改
        Major.objects.filter(major_name=old_name).update(
            major_name=major_name,
            department_id=college_id,
        )
        #修改专业后，把专业下属所有学生还有班级的学院id更改
        major_id = Major.objects.filter(major_name=major_name).first().major_id
        #获得当前专业对应的学院id
        college_id = Major.objects.filter(major_id=major_id).first().department_id
        #将当前专业所属的班级的学院id改了
        Class.objects.filter(major_id=major_id).update(
            department_id=college_id,
        )
        #更改学生的学院id
        Student.objects.filter(major_id=major_id).update(
            department_id=college_id,
        )

        Class.objects.filter(major_id=major_id)
        return JsonResponse(1,safe=False)
    except Exception as e:
        return JsonResponse(0,safe=False)

def del_one(request):
    data=json.loads(request.body)
    del_id=data['del_id']
    try:
        Major.objects.filter(major_name=del_id).delete()
        return JsonResponse(1,safe=False)
    except Exception as e:
        return JsonResponse(0,safe=False)